package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"purchase/models"
)

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type PurchaseController struct {
	beego.Controller
}

func (c *PurchaseController) List() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	query := models.DB.Model(&models.Purchase{})
	pageData := make(map[string]interface{})
	var count int64
	query.Count(&count)
	var pur []models.Purchase
	offset := (page - 1) * size
	name := c.GetString("name")
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	err := query.Offset(offset).Limit(size).Find(&pur).Order(name).Error

	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		pageData["count"] = count
		pageData["pur"] = pur
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
